package dk.jagtogjaeger.domain;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.util.Log;

public class GPSManager {

	LocationManager locationManager;
	double lat;
	double lon;
	Geocoder geoCoder;

	public void getLocation(Context context, Context baseContext,
			LocationListener ll) {

		locationManager = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 0, 0, ll);
	}
	public void closeManager(LocationListener ll){
		locationManager.removeUpdates(ll);
	}
	
	public String getMunicipality(Location location, Context baseContext) {
		geoCoder = new Geocoder(baseContext, Locale.getDefault());
		String res = "";
		try {

			List<Address> addresses = geoCoder.getFromLocation(
					location.getLatitude(), location.getLongitude(), 1);

			if (addresses.size() > 0) {
				res = addresses.get(0).getSubAdminArea();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}

	public Collection<TrackerDog> getTrackerDogsWithDistance(Location location,
			Context baseContext, Collection<TrackerDog> fetchAllTrackerDogs) {

		for (TrackerDog trackerDog : fetchAllTrackerDogs) {
			Location trackerDogLocation = new Location(LocationManager.GPS_PROVIDER);
			trackerDogLocation.setLongitude(trackerDog.getGPSY());
			trackerDogLocation.setLatitude(trackerDog.getGPSX());
			double distance = (location.distanceTo(trackerDogLocation)/1000);
			Log.d("GPSMANAGER", Double.toString(distance));
			trackerDog.setDistanceToTargetLocationInKm(distance);
		}

		return fetchAllTrackerDogs;

	}

}
